import 'package:cave_flutter/pages/cave/cave_group_chat/whl_chat_group_room_logic.dart';
import 'package:cave_flutter/whl_app.dart';
import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/bottom_controll_view/whl_bottom_control_view_logic.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/message_items/whl_image_message_item.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/message_items/whl_text_message_item.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/whl_date_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/refresh_widget.dart';
import 'package:cave_flutter/widgets/whl_app_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';

import '../../../common/chat_manager.dart';
import '../../../widgets/ls_love_progress_view.dart';
import '../../whl_chat/whl_chat_room/bottom_controll_view/whl_bottom_control_view_view.dart';
import '../../whl_chat/whl_chat_room/message_items/call_message_item.dart';
import '../../whl_chat/whl_chat_room/message_items/whl_file_message_item.dart';
import '../../whl_chat/whl_chat_room/message_items/whl_voice_message_item.dart';

class WhlChatGroupRoomPage extends StatefulWidget {
  const WhlChatGroupRoomPage({Key? key}) : super(key: key);

  @override
  State<WhlChatGroupRoomPage> createState() => _WhlChatGroupRoomPageState();
}

class _WhlChatGroupRoomPageState extends State<WhlChatGroupRoomPage>
    with WidgetsBindingObserver {
  final logic = Get.put(WhlChatGroupRoomLogic());

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void didChangeMetrics() {
    WidgetsBinding.instance.addPostFrameCallback((time) {
      if (MediaQuery.of(context).viewInsets.bottom == 0) {
        logic.isShowKeyBoard = false;
      } else {
        logic.isShowKeyBoard = true;
      }
      logic.update(['isShowKeyBoard']);
    });
    super.didChangeMetrics();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kAppColor('#FDFDFD'),
      appBar: WhlAppBar(
        centerWidget: Container(
          margin: EdgeInsets.only(right: 33.w),
          width: double.infinity,
          alignment: Alignment.center,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Flexible(
                  child: Text(
                logic.caveName,
                style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: kAppTextColor),
              )),
              UIText(
                margin: EdgeInsets.only(left: 6.w),
                gradientStartColor: kAppColor('#1C97EF'),
                gradientEndColor: kAppColor('#41B3E4'),
                gradientBegin: Alignment.centerLeft,
                gradientEnd: Alignment.centerRight,
                text: logic.caveType == '1' ? '官方' : '个人',
                radius: 99.h,
                fontSize: 10.sp,
                textColor: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 5.h, horizontal: 7.h),
              )
            ],
          ),
        ),
        rightWidget: UIRow(
          children: [
            UIImage(
              margin: EdgeInsets.only(left: 10.w, right: 20.w, top: 2.w),
              assetImage: 'icon_chat_room_more.png',
              width: 30.w,
              height: 30.w,
              onTap: () {
                logic.doClickMore();
              },
            )
          ],
        ),
      ),
      body: UIColumn(
        children: [
          Expanded(
              child: MediaQuery.removePadding(
            removeTop: true,
            removeBottom: true,
            context: context,
            child: Listener(
              onPointerMove: (event) {
                logic.isShowKeyBoard = false;
                WhlBottomControlViewLogic bottomLogic =
                    Get.find<WhlBottomControlViewLogic>();
                bottomLogic.resetAllStatus();
                hideKeyboard(context);
              },
              onPointerDown: (event) {
                logic.isShowKeyBoard = false;
                WhlBottomControlViewLogic bottomLogic =
                    Get.find<WhlBottomControlViewLogic>();
                bottomLogic.resetAllStatus();
                hideKeyboard(context);
              },
              child: Container(
                color: kAppColor('#FDFDFD'),
                child: MyRefresh(
                  controller: logic.refreshController,
                  // enablePullDown: false,
                  // enablePullUp: true,
                  onLoad: () {
                    logic.onGetMessageList();
                  },
                  child: CustomScrollView(
                    controller: logic.scrollController,
                    reverse: true,
                    shrinkWrap: true,
                    slivers: [
                      GetBuilder<WhlChatGroupRoomLogic>(builder: (logic) {
                        logic.formatMessageDatas();
                        return SliverList(
                            delegate:
                                SliverChildBuilderDelegate((context, index) {
                          NIMMessage message = logic.messageList[index];
                          return buildMessageItem(message);
                        }, childCount: logic.messageList.length));
                      })
                    ],
                  ),
                ),
              ),
            ),
          )),
          WhlBottomControlViewPage(
            isGroup: true,
            isShowKeyBoard: logic.isShowKeyBoard,
            toAccountId: logic.tid,
            caveId: logic.caveId,
          ),
        ],
      ),
    );
  }

  buildMessageItem(NIMMessage message) {
    String accountId = ChatManager.getInstance().getImAccountId();
    bool isSend = message.fromAccount == accountId;
    bool needShowTime = message.localExtension?["needShowTime"] ?? false;
    Map<String, dynamic> msgExt = message.remoteExtension ?? {};
    String avatarUrl = msgExt["avatar"] ?? "";
    List<Widget> widgetList = [
      UIImage(
        httpImage: (isSend ? WhlUserUtils.getAvatar() : avatarUrl).toImageUrl(),
        assetPlaceHolder: 'icon_app_logo.png',
        width: 44.w,
        height: 44.w,
        radius: 22.w,
        fit: BoxFit.cover,
      ),
      SizedBox(width: 10.w),
      buildMessageTypeItem(message),
      SizedBox(width: 12.w),
      if (isSend && message.status == NIMMessageStatus.sending)
        UIContainer(
          alignment: Alignment.center,
          margin: EdgeInsets.only(bottom: 15.h),
          child: CupertinoActivityIndicator(
            color: kAppMainColor,
          ),
        ),
    ];
    return Column(
      children: [
        if (needShowTime)
          UIText(
            margin: EdgeInsets.only(bottom: 17.h),
            text: WhlDateUtils.getTimeStringFromWechat(message.timestamp,
                isShowTime: true),
            fontSize: 11.sp,
            textColor: kAppSub2TextColor,
          ),
        IntrinsicHeight(
          child: UIRow(
            crossAxisAlignment: CrossAxisAlignment.start,
            padding: EdgeInsets.symmetric(horizontal: 14.w),
            mainAxisAlignment:
                isSend ? MainAxisAlignment.end : MainAxisAlignment.start,
            children: isSend ? widgetList.reversed.toList() : widgetList,
          ),
        ),
      ],
    );
  }

  buildMessageTypeItem(NIMMessage message) {
    if (message.messageType == NIMMessageType.text) {
      return WhlTextMessageItem(
        message: message,
      );
    } else if (message.messageType == NIMMessageType.audio) {
      return WhlVoiceMessageItem(message: message);
    } else if (message.messageType == NIMMessageType.image) {
      return WhlImageMessageItem(message: message);
    } else if (message.messageType == NIMMessageType.file) {
      return WhlFileMessageItem(message: message);
    } else if (message.messageType == NIMMessageType.custom) {
      Map<String, dynamic>? a = message.messageAttachment?.toMap();
      int customType = a?["customType"] ?? 0;
      if (customType == MyCustomMsgType.videoCall.tag ||
          customType == MyCustomMsgType.audioCall.tag) {
        return CallMessageItem(message: message);
      }
    }

    return Container();
  }
}
